﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Castle.DynamicProxy;
using OpenQA.Selenium;

namespace Selenium.PageToolkit
{
    public class WebElementCollectionInterceptor : IInterceptor
    {
        private readonly Func<IEnumerable<object>> _generatorFunc;
        private Type _type;
        private object _cache = null;
        public WebElementCollectionInterceptor(Func<IEnumerable<object>> generatorFunc, Type type)
        {
            _generatorFunc = generatorFunc;
            _type = type;
        }

        public void Intercept(IInvocation invocation)
        {

            _cache = _cache ?? ToListOfType(_generatorFunc()); ;
            invocation.ReturnValue = invocation.GetConcreteMethod().Invoke(_cache, invocation.Arguments);
        }

        private object ToListOfType(IEnumerable<object> items)
        {
            var lst = (IList)Activator.CreateInstance(typeof (List<>).MakeGenericType(_type));
            foreach (var item in items)
            {
                lst.Add(item);
            }
            return lst;
        }
    }
}